import * as actionType from '../actions/actionType.js'

const initState = {
  cart: wx.getStorageSync('fuckxxx') || []
}

export default (state = initState, action) => {
  switch (action.type) {
    case actionType.ADD_TO_CART: {

      if(state.cart.some(items => {
        return items.id === action.payload.id
      })) {
        state.cart = state.cart.map(item => {
          if(item.id === action.payload.id){
            item.count += action.payload.count
          }
          return item 
        })
      }else{
        state.cart.push(action.payload)
      }
      return state;
    }

    case actionType.CHANGE_COUNT_ADD:{
      console.log(action.payload)
        state.cart = state.cart.map(item => {
          if (item.id === action.payload) {
            item.count++
          }
          return item 
        })
      return state;
    }
    case actionType.CHANGE_COUNT_REDUCE: {
      state.cart = state.cart.map(item => {
        if (item.id === action.payload) {
          if(item.count > 1){
            item.count--
          }
        }
        return item
      })
      return state;
    }
    case actionType.DELETE_ITEM:{
      console.log(action.payload)
        state.cart = state.cart.filter(item => {
          return item.id !== action.payload
        })
      return state;
    }
    default:
      return state;
  }
}